# -*- coding: utf-8 -*-
'''
    :file: zips.py
    :author: -Farmer
    :url: https://blog.farmer233.top
    :date: 2021/02/18 22:14:10
'''
import os
import zipfile

from werkzeug.utils import secure_filename
from app.operation.files import FileOperation
from app.utils import is_safe_path

# 解压模块
class UnZipFile(FileOperation):
    ''' 继承自文件操作类 '''
    def __init__(self, username) -> None:
        super().__init__(username)

    def unzip(self, path:str, filename:str, zipfilename=None):
        # 目标文件路径
        zip_path = os.path.join(self.prefix, path, filename)
        if not is_safe_path(zip_path):
            raise ValueError("解压文件目录不合法")

        # 获取目标文件扩展名，仅支持zip格式解压
        filename, type_name = os.path.splitext(filename)
        if type_name != ".zip":
            raise ValueError("目标文件不支持解压")
            
        if zipfilename is None: 
            zipfilename = filename
        zipfilename = secure_filename(zipfilename)
        unzip_path = os.path.join(self.prefix, path, zipfilename)

        if not is_safe_path(unzip_path):
            raise ValueError("目标路径不合法")

        # 打开io，解压
        with zipfile.ZipFile(zip_path) as zip_file:
            zip_file.extractall(unzip_path)
            
        # 返回解压后的路径和文件名
        return os.path.join(path, zipfilename)